﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.WareHouse.CreateWareHouse;
using static BW.Mes.WinForms.WareHouse.UpdateStorageForm;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;

namespace BW.Mes.WinForms.WareHouse
{
    public partial class UpdateWareHouseForm : DevExpress.XtraEditors.XtraForm
    {
        private long _storageId; // 存储货架ID

        public UpdateWareHouseForm()
        {
            InitializeComponent();
        }

        // 带ID参数的构造函数
        public UpdateWareHouseForm(long storageId)
        {
            InitializeComponent();
            _storageId = storageId;
            this.textbm.ReadOnly = true;
            
            // 不在构造函数中加载数据，统一在Form_Load中处理
        }

        private async void UpdateWareHouseForm_Load_1(object sender, EventArgs e)
        {
            // 先加载数据源
            await LoadWareHouseDataAsync();
            await LoadWareHouseLoginAsync();
            
            // 然后加载具体数据并设置选中值
            await LoadStorageDataAsync();
        }

        /// <summary>
        /// 修改确定按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            UpdateWareHouse();
        }

        // 加载货架数据
        private async Task LoadStorageDataAsync()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync($"T3/WareHouse/GetModelWareHouse?Id={_storageId}");

                    if (response.IsSuccessStatusCode)
                    {
                        var jsonContent = await response.Content.ReadAsStringAsync();

                        // 处理API返回的数据结构
                        var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(jsonContent);
                        WareHouseModel storage = null;

                        // 检查是否有data字段
                        if (jsonObject["data"] != null)
                        {
                            string dataJson = jsonObject["data"].ToString();
                            var items = JsonConvert.DeserializeObject<WareHouseModel>(dataJson);
                            if (items != null)
                            {
                                storage = items;
                            }
                        }
                        else
                        {
                            // 直接尝试反序列化
                            storage = JsonConvert.DeserializeObject<WareHouseModel>(jsonContent);
                        }

                        if (storage != null)
                        {
                            // 回显数据到控件
                            textbm.Text = storage.WareHouseCoding;
                            textName.Text = storage.WareHouseName;
                            textBoxAddress.Text = storage.WareHouseAddress;
                            textBoxMs.Text = storage.WareHouseDescribe;
                            
                            // 直接设置下拉框值，不使用中间变量
                            gridLookUpEdit1.EditValue = storage.WareHouseStatus;
                            gridLookUpEdit2.EditValue = storage.Loginname;
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取货架数据失败:" + response.ReasonPhrase, "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("加载货架数据出错:" + ex.Message, "错误");
            }
        }

        private long _selectedGetMoidId = 0; // 保存选中的仓库ID
        private long _storageIdPeo = 0;

        /// <summary>
        /// 设置选中的仓库
        /// </summary>
        private void SetSelectedGetMoid()
        {
            if (_selectedGetMoidId > 0)
            {
                // 检查使用的是哪种控件
                if (gridLookUpEdit1 != null && gridLookUpEdit1.Properties.DataSource != null)
                {
                    gridLookUpEdit1.EditValue = _selectedGetMoidId;
                }
                // 如果是使用comboBoxEdit1，则取消注释下面的代码
                // else if (comboBoxEdit1 != null && comboBoxEdit1.Properties.DataSource != null)
                // {
                //     comboBoxEdit1.EditValue = _selectedWareHouseId;
                // }
            }

            if (_storageIdPeo > 0)
            {
                // 检查使用的是哪种控件
                if (gridLookUpEdit2 != null && gridLookUpEdit2.Properties.DataSource != null)
                {
                    gridLookUpEdit2.EditValue = _storageIdPeo;
                }
                // 如果是使用comboBoxEdit1，则取消注释下面的代码
                // else if (comboBoxEdit1 != null && comboBoxEdit1.Properties.DataSource != null)
                // {
                //     comboBoxEdit1.EditValue = _selectedWareHouseId;
                // }
            }
        }

        /// <summary>
        /// 加载仓库类型数据
        /// </summary>
        private async Task LoadWareHouseDataAsync()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T3/WareHouse/GetMoid");

                    if (response.IsSuccessStatusCode)
                    {
                        var jsonContent = await response.Content.ReadAsStringAsync();
                        var jsonObject = JsonConvert.DeserializeObject<dynamic>(jsonContent);

                        if (jsonObject["pageDatas"] != null)
                        {
                            var dataJson = jsonObject["pageDatas"].ToString();
                            var warehouses = JsonConvert.DeserializeObject<List<MoIdModel>>(dataJson);

                            if (warehouses != null && warehouses.Count > 0)
                            {
                                // 设置数据源
                                gridLookUpEdit1.Properties.DataSource = warehouses;
                                gridLookUpEdit1.Properties.DisplayMember = "MoIdName";
                                gridLookUpEdit1.Properties.ValueMember = "Id";

                                // 设置选中值
                                SetSelectedGetMoid();
                            }
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取仓库数据失败:" + response.ReasonPhrase, "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("加载仓库数据出错:" + ex.Message, "错误");
            }
        }

        
        /// <summary>
        /// 加载仓管员数据
        /// </summary>
        private async Task LoadWareHouseLoginAsync()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T1/Auth/users");

                    if (response.IsSuccessStatusCode)
                    {
                        var jsonContent = await response.Content.ReadAsStringAsync();
                        var jsonObject = JsonConvert.DeserializeObject<dynamic>(jsonContent);

                        if (jsonObject["pagingData"] != null)
                        {
                            // 将pageDatas转换为WareHouseItem列表
                            var dataJson = jsonObject["pagingData"].ToString();
                            var warehouses = JsonConvert.DeserializeObject<List<UserModel>>(dataJson);

                            // 假设您改用了gridLookUpEdit1控件
                            gridLookUpEdit2.Properties.DataSource = warehouses;
                            gridLookUpEdit2.Properties.DisplayMember = "RealName";
                            gridLookUpEdit2.Properties.ValueMember = "Id";

                            // 设置选中值
                            SetSelectedGetMoid();

                            // 配置下拉框，只显示仓库名称
                            gridLookUpEdit2.Properties.View.Columns.Clear();
                            gridLookUpEdit2.Properties.View.Columns.Add(
                                new DevExpress.XtraGrid.Columns.GridColumn
                                {
                                    FieldName = "RealName",
                                    Caption = "仓管员",
                                    Visible = true
                                }
                            );

                            // 设置默认提示文本
                            gridLookUpEdit2.Properties.NullText = "请选择仓管员";
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取仓库数据失败:" + response.ReasonPhrase, "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载仓库类型数据失败: {ex.Message}", "错误");
            }
        }




        /// <summary>
        /// 更新货架数据
        /// </summary>
        private async void UpdateWareHouse()
        {
            try
            {
                // 验证数据
                if (string.IsNullOrEmpty(textbm.Text))
                {
                    XtraMessageBox.Show("请输入货架编码", "提示");
                    return;
                }

                if (string.IsNullOrEmpty(textName.Text))
                {
                    XtraMessageBox.Show("请输入货架名称", "提示");
                    return;
                }

                if (gridLookUpEdit1.EditValue == null)
                {
                    XtraMessageBox.Show("请选择所属仓库", "提示");
                    return;
                }

                var model = new UpdateWareHouseModel
                {
                    Id = _storageId,
                    WareHouseCoding = textbm.Text,
                    WareHouseName = textName.Text,
                    WareHouseStatus = Convert.ToInt64(gridLookUpEdit1.EditValue),
                    Loginname = Convert.ToInt64(gridLookUpEdit2.EditValue),
                    WareHouseAddress = textBoxAddress.Text,
                    WareHouseDescribe = textBoxMs.Text

                };

                // 调用API更新数据
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var json = JsonConvert.SerializeObject(model);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var response = await client.PutAsync("T3/WareHouse/UpdateWareHouse", content);

                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("更新成功", "提示");
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        XtraMessageBox.Show("更新失败:" + response.ReasonPhrase, "错误");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("更新数据出错:" + ex.Message, "错误");
            }
        }

















        /// <summary>
        /// 仓库定义的实体
        /// </summary>
        public class WareHouseModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 仓库定义编码
            /// </summary>
            public string WareHouseCoding { get; set; }
            /// <summary>
            /// 仓库定义名称
            /// </summary>
            public string WareHouseName { get; set; }
            /// <summary>
            /// 仓库定义类型 外键
            /// </summary>
            public long WareHouseStatus { get; set; }
            /// <summary>
            /// 仓库定音仓管员
            /// </summary>
            public long Loginname { get; set; }
            /// <summary>
            /// 仓库定义地址
            /// </summary>
            public string WareHouseAddress { get; set; }
            /// <summary>
            /// 仓库定义描述
            /// </summary>
            public string WareHouseDescribe { get; set; }
        }

        /// <summary>
        /// 更改仓库定义的实体
        /// </summary>
        public class UpdateWareHouseModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 仓库定义编码
            /// </summary>
            public string WareHouseCoding { get; set; }
            /// <summary>
            /// 仓库定义名称
            /// </summary>
            public string WareHouseName { get; set; }
            /// <summary>
            /// 仓库定义类型 外键
            /// </summary>
            public long WareHouseStatus { get; set; }
            /// <summary>
            /// 仓库定音仓管员
            /// </summary>
            public long Loginname { get; set; }
            /// <summary>
            /// 仓库定义地址
            /// </summary>
            public string WareHouseAddress { get; set; }
            /// <summary>
            /// 仓库定义描述
            /// </summary>
            public string WareHouseDescribe { get; set; }
        }



        // 仓库类型模型
        public class MoIdModel
        {
            public long Id { get; set; }
            public string MoIdName { get; set; }
        }


        // 仓管员模型
        public class UserModel
        {
            public long Id { get; set; }
            public string RealName { get; set; }
        }







        /// <summary>
        /// 关闭修改窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}